package com.example.web;

import com.example.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/rest")
public class StudentController {

    private static final String uri = "http://localhost:9090/provider";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/findAll")
    public List<Student> findAllStudent(){
        return Arrays.asList(Objects.requireNonNull(restTemplate.getForEntity(uri + "/findAll", Student[].class).getBody()));
    }

    @GetMapping("/findById/{id}")
    public Student findStudentById(@PathVariable("id") Long id){
        return restTemplate.getForObject(uri+"/findById/{id}",Student.class,id);
    }

    @PostMapping("/save")
    public Student saveStudent(@RequestBody Student student){
        return restTemplate.postForEntity(uri+"/save",student,Student.class).getBody();
    }

    @PutMapping("/update")
    public Student updateStudent(@RequestBody Student student){
        restTemplate.put(uri+"/update",student);
        return student;
    }

    @DeleteMapping("/deleteById/{id}")
    public Boolean deleteStudentById(@PathVariable("id") Long id){
        restTemplate.delete(uri+"/deleteById/{id}",id);
        return true;
    }
}
